package vn.edu.thptduongbachmai.common;

import com.twmacinta.util.MD5;
import com.vng.zing.logger.ZLogger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author tiennv4
 */
public class Utilities {

	private static final org.apache.log4j.Logger _Logger = ZLogger.getLogger(Utilities.class);

	public static List<Integer> Shuffle(List<Integer> list) {
		List<Integer> result = new ArrayList<Integer>(list);
		Random rand = new Random();
		for (int index = 0; index < list.size(); ++index) {
			int i = rand.nextInt() % list.size();
			if (i < 0) {
				i = -i;
			}
			int temp = result.get(index);
			result.set(index, result.get(i));
			result.set(i, temp);
		}
		return result;
	}

	public static String formatDate(String format, Date d) {
		try {
			SimpleDateFormat formatter = new SimpleDateFormat(format);
			return formatter.format(d);
		} catch (Exception e) {
			return null;
		}
	}

	public static long getTime(String strDate) {
		long result = 0;
		try {
			if (strDate != null && !strDate.isEmpty()) {
				DateFormat formatter;
				Date date;
				formatter = new SimpleDateFormat("yyyy-M-d");
				date = (Date) formatter.parse(strDate);
				result = date.getTime();
			}
		} catch (ParseException e) {
			System.out.println("Exception :" + e);
		}
		return result;
	}

	public static int getDayFromDateStr(String strDate) {
		int result = 0;
		try {
			if (strDate != null && !strDate.isEmpty()) {
				DateFormat formatter;
				Date date;
				formatter = new SimpleDateFormat("yyyy-M-d");
				date = (Date) formatter.parse(strDate);
				Calendar cal = Calendar.getInstance();
				cal.setTime(date);
				result = cal.get(Calendar.DAY_OF_MONTH);
			}
		} catch (ParseException e) {
			System.out.println("Exception :" + e);
		}
		return result;
	}

	public static String getStrDate(long time, String format) {
		if (format == null || format.isEmpty()) {
			format = "yyyy-M-d";
		}
		DateFormat dateFormat = new SimpleDateFormat(format);
		Calendar cal = Calendar.getInstance();
		cal.setTimeInMillis(time);
		return dateFormat.format(cal.getTime());
	}

	public static String getStrDate(int day, int month, int year, String format) {
		if (format == null || format.isEmpty()) {
			format = "yyyy-M-d";
		}
		DateFormat dateFormat = new SimpleDateFormat(format);
		Calendar cal = Calendar.getInstance();
		cal.set(year, month, day);
		return dateFormat.format(cal.getTime());
	}

	public static String getStrFirstDateOfWeek(int day, int month, int year, String format) {
		if (format == null || format.isEmpty()) {
			format = "yyyy-M-d";
		}
		DateFormat dateFormat = new SimpleDateFormat(format);

		Calendar cal = Calendar.getInstance();
		cal.clear();

		cal.set(year, month, day);
		while (cal.get(Calendar.DAY_OF_WEEK) > cal.getFirstDayOfWeek()) {
			cal.add(Calendar.DATE, -1); // Substract 1 day until first day of week.
		}

		return dateFormat.format(cal.getTime());
	}

	public static String getStrEndDateOfWeek(int day, int month, int year, String format) {
		if (format == null || format.isEmpty()) {
			format = "yyyy-M-d";
		}
		DateFormat dateFormat = new SimpleDateFormat(format);

		Calendar cal = Calendar.getInstance();
		cal.clear();

		cal.set(year, month, day);
		while (cal.get(Calendar.DAY_OF_WEEK) > cal.getFirstDayOfWeek()) {
			cal.add(Calendar.DATE, -1); // Substract 1 day until first day of week.
		}

		cal.add(Calendar.DATE, 6);

		return dateFormat.format(cal.getTime());
	}

	public static String getStrFirstDateOfWeek(String format) {
		if (format == null || format.isEmpty()) {
			format = "yyyy-M-d";
		}
		DateFormat dateFormat = new SimpleDateFormat(format);

		Calendar cal = Calendar.getInstance();
		cal.clear();

		cal.setTimeInMillis(System.currentTimeMillis());
		while (cal.get(Calendar.DAY_OF_WEEK) > cal.getFirstDayOfWeek()) {
			cal.add(Calendar.DATE, -1); // Substract 1 day until first day of week.
		}

		return dateFormat.format(cal.getTime());
	}

	public static String getStrDateBefore(int number, String format) {
		if (format == null || format.isEmpty()) {
			format = "yyyy-M-d";
		}
		DateFormat dateFormat = new SimpleDateFormat(format);

		Calendar cal = Calendar.getInstance();
		cal.clear();

		cal.setTimeInMillis(System.currentTimeMillis());

		cal.add(Calendar.DATE, (0 - number));

		return dateFormat.format(cal.getTime());
	}

	public static String getStrEndDateOfWeek(String format) {
		if (format == null || format.isEmpty()) {
			format = "yyyy-M-d";
		}
		DateFormat dateFormat = new SimpleDateFormat(format);

		Calendar cal = Calendar.getInstance();
		cal.clear();

		cal.setTimeInMillis(System.currentTimeMillis());
		while (cal.get(Calendar.DAY_OF_WEEK) > cal.getFirstDayOfWeek()) {
			cal.add(Calendar.DATE, -1); // Substract 1 day until first day of week.
		}

		cal.add(Calendar.DATE, 7);

		return dateFormat.format(cal.getTime());
	}

	public static String escapeHTML(String html) {
		if (html != null) {
			return html.replaceAll("\\<.*?\\>", "");
		}
		return "";
	}

	public static void setCookie(String cookieName, String value, int expire, boolean httponly, String path, String domain, HttpServletRequest req, HttpServletResponse resp) {
		try {
			String strExpire = "";
			if (expire == 0) { // expire now
				Calendar cal = Calendar.getInstance();
				cal.add(Calendar.YEAR, -1);
				String ex = formatDate("EEE, dd-MMM-yyyy HH:mm:ss zzz", cal.getTime());
				strExpire = ";Expires=" + ex;
			} else if (expire > 0) {
				Calendar cal = Calendar.getInstance();
				cal.add(Calendar.MILLISECOND, expire * 1000);
				String ex = formatDate("EEE, dd-MMM-yyyy HH:mm:ss zzz", cal.getTime());
				strExpire = ";Expires=" + ex;
			}
			// else expire < -1: expires after browser is closed.

			String strHttponly = "";
			if (httponly == true) {
				strHttponly = ";HttpOnly";
			}

			//	String headerValue = cookieName + "=" + value + ";Path=" + path + ";Domain=" + domain + strExpire + strHttponly;
			String headerValue = cookieName + "=" + value + ";Path=" + path + strExpire + strHttponly;

			resp.setHeader("P3P", "CP=\"NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM\"");
			resp.addHeader("Set-Cookie", headerValue);
		} catch (Exception e) {
		}
	}

	public static String md5(String key) {
		MD5 md = new MD5(key);
		return md.asHex();
	}

	public static String sha256(String key) {

		try {
			MessageDigest md = MessageDigest.getInstance("SHA-256");
			md.update(key.getBytes());

			byte byteData[] = md.digest();

			//convert the byte to hex format method 1
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < byteData.length; i++) {
				sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
			}

			//convert the byte to hex format method 2
			StringBuilder hexString = new StringBuilder();
			for (int i = 0; i < byteData.length; i++) {
				String hex = Integer.toHexString(0xff & byteData[i]);
				if (hex.length() == 1) {
					hexString.append('0');
				}
				hexString.append(hex);
			}
			return hexString.toString();
		} catch (NoSuchAlgorithmException ex) {
			_Logger.error(null, ex);
			return null;
		}
	}
}
